#! /usr/bin/env node
import { createServer } from 'node:http'
import {
  CopilotRuntime,
  OpenAIAdapter,
  copilotRuntimeNodeHttpEndpoint,
} from '@copilotkit/runtime'

import OpenAI from 'openai'
import dotenv from 'dotenv'

dotenv.config()

console.log(process.env.OPENAI_BASE_URL, process.env.OPENAI_MODEL)

const server = createServer((req, res) => {
  const handler = copilotRuntimeNodeHttpEndpoint({
    endpoint: process.env.COPILOT_ENDPOINT,
    runtime: new CopilotRuntime({
      // actions: ({ properties, url }) => ([{
      //   name: 'echo',
      //   description: 'echo to console',
      //   parameters: [{ name: 'text', type: 'string', description: 'text to echo', required: true }],
      //   handler: async ({ text }) => {
      //     console.log(text)
      //   }
      // }])
    }),
    serviceAdapter: new OpenAIAdapter({
      keepSystemRole: true,
      model: process.env.OPENAI_MODEL,
      openai: new OpenAI({
        fetch: async (url, init) => {
          const resp = await fetch(url, init)
          // const { readable, writable } = new TransformStream()
          // resp
          // return new Response(readable)

          resp.clone().text().then(t => {
            console.log(`${url}\n${init.body}\n\n${t}`)
            // console.log('[req]: ', url, init.body)
            // console.log('[resp]: ', t)
          })
          return resp
        },
        baseURL: process.env.OPENAI_URL,
        apiKey: process.env.OPENAI_API_KEY,
      })
    }),
  })

  return handler(req, res)
})

server.listen(4000, () => {
  console.log(`Listening at http://localhost:4000${process.env.COPILOT_ENDPOINT}`)
})
